import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../theme/app_theme.dart';
import '../services/period_service.dart';
import '../models/period_model.dart';
import '../utils/date_utils.dart' as custom_date_utils;

class MinimalistModeScreen extends StatefulWidget {
  const MinimalistModeScreen({super.key});

  @override
  State<MinimalistModeScreen> createState() => MinimalistModeScreenState();
}

class MinimalistModeScreenState extends State<MinimalistModeScreen> {
  final PeriodService _periodService = PeriodService();
  TodayPrediction? _todayPrediction;
  bool _isPeriodActive = false;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final todayPrediction = await _periodService.getPredictionForToday();
      
      setState(() {
        _todayPrediction = todayPrediction;
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('加载数据失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _togglePeriodStatus() async {
    setState(() {
      _isPeriodActive = !_isPeriodActive;
    });

    if (_isPeriodActive) {
      // 开始记录经期，使用 recordPeriod 方法
      final today = DateTime.now();
      final period = Period(
        startDate: today,
        endDate: today, // 暂时设置为当天，用户可以在后续调整
        flowIntensity: 2, // 默认强度，使用整数值（1-轻，2-中，3-重）
        note: '',
        userId: 1, // 假设当前用户ID为1
      );
      await _periodService.recordPeriod(period);
    } else {
      // 结束经期，这里需要找到最近的经期记录并更新
      // 简化处理，实际应该查找并更新最近的经期记录
    }
    
    
    _loadData();
    
    
    _notifyRecordScreen();
  }
  
  void _notifyRecordScreen() {
    
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool('periodStatusChanged', true);
      await prefs.setInt('lastPeriodStatusChange', DateTime.now().millisecondsSinceEpoch);
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        backgroundColor: AppTheme.background,
        body: Center(
          child: CircularProgressIndicator(color: AppTheme.primaryColor),
        ),
      );
    }

    final cycleInfo = _todayPrediction?.cycleInfo as CycleInfo?;
    final daysUntilNextPeriod = cycleInfo?.daysUntilNextPeriod ?? 7;
    final nextPeriodDate = cycleInfo?.nextPeriodDate ?? DateTime.now().add(Duration(days: 7));
    final pregnancyRate = cycleInfo?.pregnancyRate ?? 3.2;
    final nextPeriodDateStr = custom_date_utils.DateUtils.formatDate(nextPeriodDate);

    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        backgroundColor: AppTheme.white,
        elevation: 0,
        title: const Text(
          '月伴·极简',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimary,
          ),
        ),
        centerTitle: true,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: Column(
            children: [
              
              Container(
                margin: const EdgeInsets.all(16),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.primaryColor,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '距月经开始$daysUntilNextPeriod天',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: AppTheme.white,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Row(
                          children: [
                            Text(
                              '预测经期开始$nextPeriodDateStr',
                              style: TextStyle(
                                fontSize: 14,
                                color: AppTheme.white.withValues(alpha: 0.9),
                              ),
                            ),
                            Icon(Icons.arrow_forward,
                                color: AppTheme.white.withValues(alpha: 0.9), size: 16),
                          ],
                        ),
                      ],
                    ),
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: AppTheme.white.withValues(alpha: 0.2),
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Column(
                        children: [
                          Text(
                            '怀孕几率',
                            style: TextStyle(
                              fontSize: 12,
                              color: AppTheme.white.withValues(alpha: 0.9),
                            ),
                          ),
                          Text(
                            '${pregnancyRate.toStringAsFixed(1)}%',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: AppTheme.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              
              Container(
                margin: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.water_drop_outlined,
                            color: AppTheme.primaryColor, size: 20),
                        const SizedBox(width: 8),
                        Text(
                          '月经来了',
                          style: TextStyle(
                            fontSize: 16,
                            color: AppTheme.textPrimary,
                          ),
                        ),
                      ],
                    ),
                    Row(
                      children: [
                        GestureDetector(
                          onTap: _isPeriodActive ? null : _togglePeriodStatus,
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                            decoration: BoxDecoration(
                              color: _isPeriodActive ? AppTheme.primaryColor : AppTheme.lightGray,
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: Text(
                              '是',
                              style: TextStyle(
                                fontSize: 14,
                                color: _isPeriodActive ? AppTheme.white : AppTheme.textSecondary,
                                fontWeight: _isPeriodActive ? FontWeight.bold : FontWeight.normal,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 12),
                        GestureDetector(
                          onTap: _isPeriodActive ? _togglePeriodStatus : null,
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
                            decoration: BoxDecoration(
                              color: !_isPeriodActive ? AppTheme.primaryColor : AppTheme.lightGray,
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: Text(
                              '否',
                              style: TextStyle(
                                fontSize: 14,
                                color: !_isPeriodActive ? AppTheme.white : AppTheme.textSecondary,
                                fontWeight: !_isPeriodActive ? FontWeight.bold : FontWeight.normal,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              
              Container(
                margin: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    
                    const Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '今日预测',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: AppTheme.textPrimary,
                          ),
                        ),
                        Icon(Icons.arrow_forward, color: AppTheme.textSecondary, size: 16),
                      ],
                    ),
                    const SizedBox(height: 16),
                    
                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        
                        Expanded(
                          flex: 2,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                '症状',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: AppTheme.textSecondary,
                                ),
                              ),
                              const SizedBox(height: 12),
                              _buildSymptomsGrid(),
                            ],
                          ),
                        ),
                        
                        
                        Expanded(
                          flex: 1,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                '白带',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: AppTheme.textSecondary,
                                ),
                              ),
                              const SizedBox(height: 12),
                              _buildDischargeIndicator(),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              
              
              Container(
                margin: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '经期健康度',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: AppTheme.textPrimary,
                      ),
                    ),
                    const SizedBox(height: 8),
                    FutureBuilder<CycleInfo>(
                      future: _periodService.getCycleInfo(),
                      builder: (context, snapshot) {
                        final healthScore = snapshot.hasData ? snapshot.data!.healthScore : 0;
                        final healthStatus = snapshot.hasData ? snapshot.data!.healthStatus : _getHealthStatus(healthScore);
                        
                        return Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '$healthScore分',
                              style: const TextStyle(
                                fontSize: 24,
                                fontWeight: FontWeight.bold,
                                color: AppTheme.primaryColor,
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                              decoration: BoxDecoration(
                                color: _getHealthStatusColor(healthStatus).withValues(alpha: 0.1),
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: Text(
                                healthStatus,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: _getHealthStatusColor(healthStatus),
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ],
                        );
                      },
                    ),
                  ],
                ),
              ),
              
              
              Container(
                margin: const EdgeInsets.only(left: 16, right: 16, bottom: 80),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '周期变化',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: AppTheme.textPrimary,
                          ),
                        ),
                        Icon(Icons.arrow_forward, color: AppTheme.textSecondary, size: 16),
                      ],
                    ),
                    const SizedBox(height: 16),
                    
                    
                    FutureBuilder<List<Period>>(
                      future: _periodService.getRecentCycles(),
                      builder: (context, snapshot) {
                        if (snapshot.connectionState == ConnectionState.waiting) {
                          return const Center(child: CircularProgressIndicator());
                        }
                        
                        if (snapshot.hasError || snapshot.data == null || snapshot.data!.isEmpty) {
                          return const Text(
                            '暂无周期记录',
                            style: TextStyle(
                              fontSize: 14,
                              color: AppTheme.textSecondary,
                            ),
                          );
                        }
                        
                        final cycles = snapshot.data!;
                        
                        return Column(
                          children: [
                            for (int i = 0; i < cycles.length && i < 3; i++)
                              Column(
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        custom_date_utils.DateUtils.formatDate(cycles[i].startDate),
                                        style: const TextStyle(
                                          fontSize: 14,
                                          color: AppTheme.textSecondary,
                                        ),
                                      ),
                                      Expanded(
                                        flex: 1,
                                        child: Container(
                                          margin: const EdgeInsets.symmetric(horizontal: 16),
                                          height: 12,
                                          decoration: BoxDecoration(
                                            color: AppTheme.primaryColor, // 直接使用主色调，移除死代码条件
                                            borderRadius: BorderRadius.circular(6),
                                          ),
                                          alignment: Alignment.center,
                                          child: Text(
                                              '${cycles[i].endDate.difference(cycles[i].startDate).inDays + 1}天',
                                            style: TextStyle(
                                              fontSize: 10,
                                              color: Colors.white,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                        ),
                                      ),
                                      Text(
                                        '正常', // 暂时硬编码为正常状态
                                        style: TextStyle(
                                          fontSize: 14,
                                          color: Colors.green,
                                        ),
                                      ),
                                    ],
                                  ),
                                  if (i < cycles.length - 1 && i < 2) const SizedBox(height: 16),
                                ],
                              ),
                          ],
                        );
                      },
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSymptomsGrid() {
    final symptoms = _todayPrediction?.symptoms ?? [];
    
    if (symptoms.isEmpty) {
      return const Text(
        '无特殊症状',
        style: TextStyle(
          fontSize: 12,
          color: AppTheme.textSecondary,
        ),
      );
    }

    return Column(
      children: [
        for (int i = 0; i < symptoms.length; i += 2)
          Row(
            children: [
              if (i < symptoms.length)
                Expanded(
                  child: _buildSymptomItem(symptoms[i]),
                ),
              if (i + 1 < symptoms.length)
                Expanded(
                  child: _buildSymptomItem(symptoms[i + 1]),
                ),
            ],
          ),
      ],
    );
  }

  Widget _buildSymptomItem(String symptom) {
    return Column(
      children: [
        Container(
          width: 48,
          height: 48,
          decoration: BoxDecoration(
            color: AppTheme.primaryColor.withValues(alpha: 0.1),
            borderRadius: BorderRadius.circular(24),
          ),
          alignment: Alignment.center,
          child: Icon(_getSymptomIcon(symptom),
              color: AppTheme.primaryColor, size: 24),
        ),
        const SizedBox(height: 8),
        Text(
          symptom,
          style: const TextStyle(
            fontSize: 12,
            color: AppTheme.textSecondary,
          ),
        ),
      ],
    );
  }

  IconData _getSymptomIcon(String symptom) {
    switch (symptom) {
      case '心烦意乱':
        return Icons.sentiment_dissatisfied_outlined;
      case '失眠':
        return Icons.bed_outlined;
      case '乳房胀痛':
        return Icons.favorite_border;
      case '白带增多':
        return Icons.cloud_outlined;
      case '情绪波动':
        return Icons.mood_outlined;
      case '疲劳':
        return Icons.energy_savings_leaf_outlined;
      default:
        return Icons.medical_services_outlined;
    }
  }

  Widget _buildDischargeIndicator() {
    final discharge = _todayPrediction?.discharge ?? '正常';
    
    return Column(
      children: [
        Container(
          width: 48,
          height: 48,
          decoration: BoxDecoration(
            color: AppTheme.primaryColor.withValues(alpha: 0.1),
            borderRadius: BorderRadius.circular(24),
          ),
          alignment: Alignment.center,
          child: Icon(Icons.cloud_outlined,
              color: AppTheme.primaryColor, size: 24),
        ),
        const SizedBox(height: 8),
        Text(
          discharge,
          style: const TextStyle(
            fontSize: 12,
            color: AppTheme.textSecondary,
          ),
        ),
      ],
    );
  }





  
  String _getHealthStatus(int score) {
    if (score >= 90) return '优秀';
    if (score >= 80) return '良好';
    if (score >= 70) return '一般';
    if (score >= 60) return '较差';
    return '差';
  }

  
  Color _getHealthStatusColor(String status) {
    switch (status) {
      case '优秀':
        return Colors.green;
      case '良好':
        return Colors.blue;
      case '一般':
        return Colors.orange;
      case '较差':
        return Colors.red;
      case '差':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }
}